package com.andaily.springoauth.web;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.andaily.springoauth.service.OauthService;
import com.andaily.springoauth.service.dto.AuthAccessTokenDto;
import com.andaily.springoauth.service.dto.UserDto;

/**
 * 客户端模式业务处理控制层
 */
@Controller
public class ClientCredentialsController {

	private static final Logger	LOG	= LoggerFactory.getLogger(ClientCredentialsController.class);

	@Value("#{properties['access-token-uri']}")
	private String				accessTokenUri;

	@Value("#{properties['unityUserInfoUri']}")
	private String				unityUserInfoUri;

	@Autowired
	private OauthService		oauthService;

	/*
	 * Entrance: step-1
	 */
	@RequestMapping(value = "client_credentials", method = RequestMethod.GET)
	public String password(Model model) {
		LOG.debug("Go to 'client_credentials' page, accessTokenUri = {}", accessTokenUri);
		model.addAttribute("accessTokenUri", accessTokenUri);
		model.addAttribute("unityUserInfoUri", unityUserInfoUri);
		return "client_credentials";
	}

	@RequestMapping(value = "credentials_access_token")
	public void getAccessToken(AuthAccessTokenDto authAccessTokenDto, HttpServletResponse response) {
		Map<String, Object> resultMap = oauthService.retrieveCredentialsAccessTokenDto(authAccessTokenDto);
		UserDto userDto = (UserDto) resultMap.get("userDto");
		if ((boolean) resultMap.get("flag")) {
			if (userDto.error()) {
				System.out.println(userDto.getErrorDescription());
			} else {
				System.out.println(userDto.getUsername());
			}
		} else {
			System.out.println(userDto.getErrorDescription());
		}
	}
}
